// 生产环境作为默认原始地址
const ORIGIN_URL = 'https://console-gms-api-dev.ntplat.com';

// 初始化规则
chrome.runtime.onInstalled.addListener(() => {
  // 加载保存的环境或使用默认
  chrome.storage.local.get('currentEnv', (result) => {
    const targetUrl = result.target || result.targets[0] || result.url;
    updateRules(result.url, targetUrl).then(success => success ? injectToCurrentTab(targetUrl) : false)
  });
});

// 监听环境切换消息  点击按钮切换的时候
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'switchEnv') {
    let env = message.env
    const targetUrl = env.target || env.targets[0] || env.url;
    updateRules(env.url, targetUrl).then(success => success ? injectToCurrentTab(env) : false)
    sendResponse({ success: true });// 
  }
});

// 更新网络请求规则
function updateRules(origin, target) {
  return new Promise((resolve, reject) => {
    // 清除现有动态规则
    chrome.declarativeNetRequest.getDynamicRules((rules) => {
      const ruleIds = rules.map(rule => rule.id);
      console.log('ruleIds:', ruleIds);

      chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: ruleIds,
        addRules: createRules(origin, target),

      }, () => {
        if (chrome.runtime.lastError) {
          console.error("规则更新失败:", chrome.runtime.lastError);
          resolve(false);
        } else {
          console.log("规则更新成功:", 666);
          resolve(true);
        }
      });
    });
  });

}

// 创建重定向规则
function createRules(origin, target) {
  console.log('createRules:', origin, target);

  // 只在目标不是原始地址时创建规则
  if (origin === target) {
    return [];
  }

  return [
    {
      id: 1,
      priority: 1,
      action: {
        type: 'redirect',
        redirect: {
          regexSubstitution: target + '\\1'
        }
      },
      condition: {
        regexFilter: `${origin}(.*)`,
        resourceTypes: ["main_frame",    // 主页面
          "sub_frame",     // 子框架
          "xmlhttprequest", // AJAX请求（包括fetch的底层实现）
          "script",        // 脚本文件
          "stylesheet",    // 样式表
          "image",         // 图片资源
          "font",          // 字体文件
          "media",         // 媒体文件
          "websocket"      // WebSocket连接
        ]
      }
    }
  ];
}
// 监听当前标签页并注入脚本
function injectToCurrentTab(data) {
  return new Promise((resolve) => {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      console.log(tabs);

      if (tabs.length > 0) {
        injectEnvScript(tabs[0].id, data).then(resolve);
        // resolve(true);
      } else {
        resolve(false);
      }
    });
  });
}
// 注入脚本
function injectEnvScript(tabId, data) {
  console.log(data, '---666', tabId);

  // return
  return new Promise((resolve) => {
    chrome.scripting.executeScript({
      target: { tabId: tabId, allFrames: true },
      world: "MAIN",
      injectImmediately: true,
      args: [data],// 传入参数
      func: (data) => {
        try {
          if (CONFIG) {
            let url = data.target || data.targets[0] || data.url
            let env = "";
            if (url.includes("-dev.")) {
              env = "-dev";
            } else if (url.includes("-qa.")) {
              env = "-qa";
            }
            let utilsUrl = `https://utils${env}.newtypegames.com`;
            let SSOLogoutUrl = `https://sso-api${env}.taiyouxi.cn/server/oauth`;
            let SSOUrl = `https://sso${env}.taiyouxi.cn/login`;

            let obj = {
              baseUrl: url,
              utilsUrl,
              SSOLogoutUrl,
              SSOUrl,
            }
            console.log('CONFIG', CONFIG);
            CONFIG = obj
          }
        } catch (error) {

        }
        console.log("环境切换成功，当前baseUrl:");
        return true;
      }
    }, (results) => {
      if (chrome.runtime.lastError) {
        console.error("脚本注入失败:", chrome.runtime.lastError);
        resolve(false);
      } else {
        resolve(true);
      }
    })
  })
}